// Copyright (c) 2004, AccuSoft Corporation. All rights reserved.

using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

using ImageGear.Core;
using ImageGear.Processing;
using ImageGear.Formats;
using ImageGear.TWAIN;
using ImageGear.Windows.Forms;
using Dimok;

namespace TWAIN {
	public class MainForm :System.Windows.Forms.Form {

		#region Properties
		private static readonly string applicationTitle =
	"ImageGear for .NET TWAIN Scanning Sample";
		private IContainer components;

		private System.Windows.Forms.MainMenu mainMenu;
		private System.Windows.Forms.MenuItem menuItemFile;
		private System.Windows.Forms.MenuItem menuItemExit;
		private System.Windows.Forms.MenuItem menuItemScan;
		private System.Windows.Forms.MenuItem menuItemSelectSource;
		private System.Windows.Forms.MenuItem menuItemSettings;
		private System.Windows.Forms.MenuItem menuItemUseUI;
		private System.Windows.Forms.MenuItem menuItemSinglePageAcquire;
		private System.Windows.Forms.MenuItem menuItemMultiPageAcquire;
		private System.Windows.Forms.MenuItem menuHelp;
		private System.Windows.Forms.MenuItem menuAbout;

		private System.Windows.Forms.MenuItem menuScanSeparator;
		private System.Windows.Forms.MenuItem menuSavePage;

		private ImageGear.Windows.Forms.ImGearPageView imGearPageView;

		private int currImGearDocPageNum = 0;
		private ImGearDocument currImGearDoc = null;
		private ImGearPage currImGearPage = null;
		private System.Windows.Forms.MenuItem menuFileSeparator1;
		static private ImGearTWAIN imGearTWAIN = null;
		private System.Windows.Forms.MenuItem menuItemView;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.MenuItem menuItemViewFirstPage;
		private System.Windows.Forms.MenuItem menuItemViewPreviousPage;
		private System.Windows.Forms.MenuItem menuItemViewNextPage;
		private System.Windows.Forms.MenuItem menuItemViewLastPage;
		private System.Windows.Forms.MenuItem mnuScanParams;
		private System.Windows.Forms.MenuItem menuItemUseEvents;
		static private bool isSourceOpen = false;
		private System.Windows.Forms.MenuItem menuItemMultiPageAcquireEvents;
		private System.Windows.Forms.MenuItem menuSaveDocument;
		private MenuItem mnuScanContinuous;
		private MenuItem menuItem2;
		private ToolStrip toolStrip1;
		private ToolStripButton tbbPrev;
		private ToolStripButton tbbNext;
		private CheckBox chkCopyBarCode;
		private DateTimePicker pmDate;
		private TextBox lblBarCodes;
		private TextBox txtBarCode;
		private Label lblPMDate;
		private Label lblBarCodesHeader;
		private ToolStripButton tbbClearAll;
		private ToolStripButton tbbSave;
		private ToolStripLabel tbbBarCodeThreadsCount;
		private ToolStripSeparator toolStripSeparator2;
		private ToolStripButton tbbScan;
		private ToolStripSeparator toolStripSeparator1;
		private System.Windows.Forms.Timer timerAcquire;
		private ToolStripLabel tbbPageCount;
		private ToolStripLabel toolStripLabel1;
		private ToolStripLabel toolStripLabel2;
		private ToolStripLabel tbbPageCurrent;
		private MenuItem mnuOutputFolder;
		private bool bEventsEnabled = false;

		#endregion

		#region Constructor
		public MainForm() {
			InitializeComponent();

			this.Text = applicationTitle;

			imGearTWAIN = new ImGearTWAIN();
			imGearTWAIN.WindowHandle = this.Handle;
			imGearTWAIN.UseUI = menuItemUseUI.Checked;
		}

		protected override void Dispose(bool disposing) {
			if(disposing) {
				if(components != null)
					components.Dispose();
			}

			base.Dispose(disposing);
		}

		#endregion
		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent() {
			this.components = new System.ComponentModel.Container();
			System.Windows.Forms.Timer timerBarCodeBox;
			System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
			this.mainMenu = new System.Windows.Forms.MainMenu(this.components);
			this.menuItemFile = new System.Windows.Forms.MenuItem();
			this.menuSavePage = new System.Windows.Forms.MenuItem();
			this.menuSaveDocument = new System.Windows.Forms.MenuItem();
			this.menuFileSeparator1 = new System.Windows.Forms.MenuItem();
			this.menuItemExit = new System.Windows.Forms.MenuItem();
			this.menuItemView = new System.Windows.Forms.MenuItem();
			this.menuItem1 = new System.Windows.Forms.MenuItem();
			this.menuItemViewFirstPage = new System.Windows.Forms.MenuItem();
			this.menuItemViewPreviousPage = new System.Windows.Forms.MenuItem();
			this.menuItemViewNextPage = new System.Windows.Forms.MenuItem();
			this.menuItemViewLastPage = new System.Windows.Forms.MenuItem();
			this.menuItemScan = new System.Windows.Forms.MenuItem();
			this.menuItemSinglePageAcquire = new System.Windows.Forms.MenuItem();
			this.menuItemMultiPageAcquire = new System.Windows.Forms.MenuItem();
			this.menuItemMultiPageAcquireEvents = new System.Windows.Forms.MenuItem();
			this.mnuScanContinuous = new System.Windows.Forms.MenuItem();
			this.menuScanSeparator = new System.Windows.Forms.MenuItem();
			this.menuItemSelectSource = new System.Windows.Forms.MenuItem();
			this.menuItem2 = new System.Windows.Forms.MenuItem();
			this.menuItemSettings = new System.Windows.Forms.MenuItem();
			this.menuItemUseUI = new System.Windows.Forms.MenuItem();
			this.menuItemUseEvents = new System.Windows.Forms.MenuItem();
			this.mnuScanParams = new System.Windows.Forms.MenuItem();
			this.mnuOutputFolder = new System.Windows.Forms.MenuItem();
			this.menuHelp = new System.Windows.Forms.MenuItem();
			this.menuAbout = new System.Windows.Forms.MenuItem();
			this.imGearPageView = new ImageGear.Windows.Forms.ImGearPageView();
			this.toolStrip1 = new System.Windows.Forms.ToolStrip();
			this.tbbPrev = new System.Windows.Forms.ToolStripButton();
			this.tbbClearAll = new System.Windows.Forms.ToolStripButton();
			this.tbbBarCodeThreadsCount = new System.Windows.Forms.ToolStripLabel();
			this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel();
			this.tbbPageCount = new System.Windows.Forms.ToolStripLabel();
			this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel();
			this.tbbNext = new System.Windows.Forms.ToolStripButton();
			this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
			this.tbbScan = new System.Windows.Forms.ToolStripButton();
			this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
			this.tbbSave = new System.Windows.Forms.ToolStripButton();
			this.tbbPageCurrent = new System.Windows.Forms.ToolStripLabel();
			this.chkCopyBarCode = new System.Windows.Forms.CheckBox();
			this.pmDate = new System.Windows.Forms.DateTimePicker();
			this.lblBarCodes = new System.Windows.Forms.TextBox();
			this.txtBarCode = new System.Windows.Forms.TextBox();
			this.lblPMDate = new System.Windows.Forms.Label();
			this.lblBarCodesHeader = new System.Windows.Forms.Label();
			this.timerAcquire = new System.Windows.Forms.Timer(this.components);
			timerBarCodeBox = new System.Windows.Forms.Timer(this.components);
			this.toolStrip1.SuspendLayout();
			this.SuspendLayout();
			// 
			// timerBarCodeBox
			// 
			timerBarCodeBox.Enabled = true;
			timerBarCodeBox.Interval = 2000;
			timerBarCodeBox.Tick += new System.EventHandler(this.timerBarCodeBox_Tick);
			// 
			// mainMenu
			// 
			this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemFile,
            this.menuItemView,
            this.menuItemScan,
            this.menuItemSettings,
            this.menuHelp});
			// 
			// menuItemFile
			// 
			this.menuItemFile.Index = 0;
			this.menuItemFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuSavePage,
            this.menuSaveDocument,
            this.menuFileSeparator1,
            this.menuItemExit});
			this.menuItemFile.Text = "&File";
			// 
			// menuSavePage
			// 
			this.menuSavePage.Enabled = false;
			this.menuSavePage.Index = 0;
			this.menuSavePage.Shortcut = System.Windows.Forms.Shortcut.CtrlS;
			this.menuSavePage.Text = "&Save Page...";
			this.menuSavePage.Click += new System.EventHandler(this.menuSavePage_Click);
			// 
			// menuSaveDocument
			// 
			this.menuSaveDocument.Enabled = false;
			this.menuSaveDocument.Index = 1;
			this.menuSaveDocument.Text = "Save &Document...";
			this.menuSaveDocument.Click += new System.EventHandler(this.menuSaveDocument_Click);
			// 
			// menuFileSeparator1
			// 
			this.menuFileSeparator1.Index = 2;
			this.menuFileSeparator1.Text = "-";
			// 
			// menuItemExit
			// 
			this.menuItemExit.Index = 3;
			this.menuItemExit.Text = "E&xit";
			this.menuItemExit.Click += new System.EventHandler(this.Exit);
			// 
			// menuItemView
			// 
			this.menuItemView.Index = 1;
			this.menuItemView.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItem1,
            this.menuItemViewFirstPage,
            this.menuItemViewPreviousPage,
            this.menuItemViewNextPage,
            this.menuItemViewLastPage});
			this.menuItemView.Text = "&View";
			this.menuItemView.Popup += new System.EventHandler(this.menuItemView_Popup);
			// 
			// menuItem1
			// 
			this.menuItem1.Index = 0;
			this.menuItem1.Text = "&Warnings...";
			this.menuItem1.Click += new System.EventHandler(this.ShowWarnings);
			// 
			// menuItemViewFirstPage
			// 
			this.menuItemViewFirstPage.Index = 1;
			this.menuItemViewFirstPage.Text = "&First Page";
			this.menuItemViewFirstPage.Click += new System.EventHandler(this.menuItemViewFirstPage_Click);
			// 
			// menuItemViewPreviousPage
			// 
			this.menuItemViewPreviousPage.Index = 2;
			this.menuItemViewPreviousPage.Text = "&Previous Page";
			this.menuItemViewPreviousPage.Click += new System.EventHandler(this.menuItemViewPreviousPage_Click);
			// 
			// menuItemViewNextPage
			// 
			this.menuItemViewNextPage.Index = 3;
			this.menuItemViewNextPage.Text = "&Next Page";
			this.menuItemViewNextPage.Click += new System.EventHandler(this.menuItemViewNextPage_Click);
			// 
			// menuItemViewLastPage
			// 
			this.menuItemViewLastPage.Index = 4;
			this.menuItemViewLastPage.Text = "&Last Page";
			this.menuItemViewLastPage.Click += new System.EventHandler(this.menuItemViewLastPage_Click);
			// 
			// menuItemScan
			// 
			this.menuItemScan.Index = 2;
			this.menuItemScan.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemSinglePageAcquire,
            this.menuItemMultiPageAcquire,
            this.menuItemMultiPageAcquireEvents,
            this.mnuScanContinuous,
            this.menuScanSeparator,
            this.menuItemSelectSource,
            this.menuItem2});
			this.menuItemScan.Text = "S&can";
			this.menuItemScan.Popup += new System.EventHandler(this.menuItemScan_Popup);
			// 
			// menuItemSinglePageAcquire
			// 
			this.menuItemSinglePageAcquire.Index = 0;
			this.menuItemSinglePageAcquire.Text = "Acquire &Single Page";
			this.menuItemSinglePageAcquire.Click += new System.EventHandler(this.AcquireSinglePage);
			// 
			// menuItemMultiPageAcquire
			// 
			this.menuItemMultiPageAcquire.Index = 1;
			this.menuItemMultiPageAcquire.Text = "Acquire &Multi Page to Document";
			this.menuItemMultiPageAcquire.Click += new System.EventHandler(this.AcquireMultiPage);
			// 
			// menuItemMultiPageAcquireEvents
			// 
			this.menuItemMultiPageAcquireEvents.Index = 2;
			this.menuItemMultiPageAcquireEvents.Text = "Acquire Multi Page to Events";
			this.menuItemMultiPageAcquireEvents.Click += new System.EventHandler(this.AcquireMultiPageEvents);
			// 
			// mnuScanContinuous
			// 
			this.mnuScanContinuous.Index = 3;
			this.mnuScanContinuous.Text = "Scan Continuous";
			this.mnuScanContinuous.Click += new System.EventHandler(this.mnuScanContinuous_Click);
			// 
			// menuScanSeparator
			// 
			this.menuScanSeparator.Index = 4;
			this.menuScanSeparator.Text = "-";
			// 
			// menuItemSelectSource
			// 
			this.menuItemSelectSource.Index = 5;
			this.menuItemSelectSource.Text = "Select S&ource...";
			this.menuItemSelectSource.Click += new System.EventHandler(this.SelectSource);
			// 
			// menuItem2
			// 
			this.menuItem2.Index = 6;
			this.menuItem2.Text = "Scan Continuose";
			// 
			// menuItemSettings
			// 
			this.menuItemSettings.Index = 3;
			this.menuItemSettings.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemUseUI,
            this.menuItemUseEvents,
            this.mnuScanParams,
            this.mnuOutputFolder});
			this.menuItemSettings.Text = "&Settings";
			this.menuItemSettings.Popup += new System.EventHandler(this.menuItemSettings_Popup);
			// 
			// menuItemUseUI
			// 
			this.menuItemUseUI.Index = 0;
			this.menuItemUseUI.Text = "Use &UI";
			this.menuItemUseUI.Click += new System.EventHandler(this.UseUI);
			// 
			// menuItemUseEvents
			// 
			this.menuItemUseEvents.Index = 1;
			this.menuItemUseEvents.Text = "Use &Events";
			this.menuItemUseEvents.Click += new System.EventHandler(this.menuItemUseEvents_Click);
			// 
			// mnuScanParams
			// 
			this.mnuScanParams.Index = 2;
			this.mnuScanParams.Text = "Scan &Parameters...";
			this.mnuScanParams.Click += new System.EventHandler(this.mnuScanParams_Click);
			// 
			// mnuOutputFolder
			// 
			this.mnuOutputFolder.Index = 3;
			this.mnuOutputFolder.Text = "Output Folder";
			this.mnuOutputFolder.Click += new System.EventHandler(this.mnuOutputFolder_Click);
			// 
			// menuHelp
			// 
			this.menuHelp.Index = 4;
			this.menuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuAbout});
			this.menuHelp.Text = "&Help";
			// 
			// menuAbout
			// 
			this.menuAbout.Index = 0;
			this.menuAbout.Shortcut = System.Windows.Forms.Shortcut.F1;
			this.menuAbout.Text = "&About...";
			this.menuAbout.Click += new System.EventHandler(this.ShowAboutBox);
			// 
			// imGearPageView
			// 
			this.imGearPageView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
									| System.Windows.Forms.AnchorStyles.Left)
									| System.Windows.Forms.AnchorStyles.Right)));
			this.imGearPageView.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
			this.imGearPageView.BackColor = System.Drawing.SystemColors.Control;
			this.imGearPageView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
			this.imGearPageView.Display = null;
			this.imGearPageView.Location = new System.Drawing.Point(0, 28);
			this.imGearPageView.Name = "imGearPageView";
			this.imGearPageView.Page = null;
			this.imGearPageView.Size = new System.Drawing.Size(574, 744);
			this.imGearPageView.TabIndex = 0;
			// 
			// toolStrip1
			// 
			this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.tbbPrev,
            this.tbbClearAll,
            this.tbbBarCodeThreadsCount,
            this.toolStripLabel2,
            this.tbbPageCount,
            this.toolStripLabel1,
            this.tbbNext,
            this.toolStripSeparator2,
            this.tbbScan,
            this.toolStripSeparator1,
            this.tbbSave,
            this.tbbPageCurrent});
			this.toolStrip1.Location = new System.Drawing.Point(0, 0);
			this.toolStrip1.Name = "toolStrip1";
			this.toolStrip1.Size = new System.Drawing.Size(853, 25);
			this.toolStrip1.TabIndex = 1;
			this.toolStrip1.Text = "toolStrip1";
			this.toolStrip1.Paint += new System.Windows.Forms.PaintEventHandler(this.toolStrip1_Paint);
			// 
			// tbbPrev
			// 
			this.tbbPrev.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
			this.tbbPrev.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
			this.tbbPrev.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tbbPrev.Name = "tbbPrev";
			this.tbbPrev.Size = new System.Drawing.Size(49, 22);
			this.tbbPrev.Text = "<<Prev";
			this.tbbPrev.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage;
			this.tbbPrev.Click += new System.EventHandler(this.tbbPrev_Click);
			// 
			// tbbClearAll
			// 
			this.tbbClearAll.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
			this.tbbClearAll.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
			this.tbbClearAll.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tbbClearAll.Name = "tbbClearAll";
			this.tbbClearAll.Size = new System.Drawing.Size(50, 22);
			this.tbbClearAll.Text = "Clear All";
			this.tbbClearAll.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage;
			this.tbbClearAll.Click += new System.EventHandler(this.tbbClearAll_Click);
			// 
			// tbbBarCodeThreadsCount
			// 
			this.tbbBarCodeThreadsCount.Name = "tbbBarCodeThreadsCount";
			this.tbbBarCodeThreadsCount.Size = new System.Drawing.Size(13, 22);
			this.tbbBarCodeThreadsCount.Text = "0";
			// 
			// toolStripLabel2
			// 
			this.toolStripLabel2.Name = "toolStripLabel2";
			this.toolStripLabel2.Size = new System.Drawing.Size(11, 22);
			this.toolStripLabel2.Text = "/";
			// 
			// tbbPageCount
			// 
			this.tbbPageCount.Name = "tbbPageCount";
			this.tbbPageCount.Size = new System.Drawing.Size(13, 22);
			this.tbbPageCount.Text = "0";
			// 
			// toolStripLabel1
			// 
			this.toolStripLabel1.Name = "toolStripLabel1";
			this.toolStripLabel1.Size = new System.Drawing.Size(36, 22);
			this.toolStripLabel1.Text = "Pages";
			// 
			// tbbNext
			// 
			this.tbbNext.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
			this.tbbNext.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
			this.tbbNext.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tbbNext.Name = "tbbNext";
			this.tbbNext.Size = new System.Drawing.Size(50, 22);
			this.tbbNext.Text = "Next>>";
			this.tbbNext.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage;
			this.tbbNext.Click += new System.EventHandler(this.tbbNext_Click);
			// 
			// toolStripSeparator2
			// 
			this.toolStripSeparator2.Name = "toolStripSeparator2";
			this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25);
			// 
			// tbbScan
			// 
			this.tbbScan.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
			this.tbbScan.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
			this.tbbScan.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tbbScan.Name = "tbbScan";
			this.tbbScan.Size = new System.Drawing.Size(34, 22);
			this.tbbScan.Text = "Scan";
			this.tbbScan.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage;
			this.tbbScan.Click += new System.EventHandler(this.tbbScan_Click);
			// 
			// toolStripSeparator1
			// 
			this.toolStripSeparator1.Name = "toolStripSeparator1";
			this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
			// 
			// tbbSave
			// 
			this.tbbSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
			this.tbbSave.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
			this.tbbSave.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tbbSave.Name = "tbbSave";
			this.tbbSave.Size = new System.Drawing.Size(35, 22);
			this.tbbSave.Text = "Save";
			this.tbbSave.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage;
			this.tbbSave.Click += new System.EventHandler(this.tbbSave_Click);
			// 
			// tbbPageCurrent
			// 
			this.tbbPageCurrent.Name = "tbbPageCurrent";
			this.tbbPageCurrent.Size = new System.Drawing.Size(13, 22);
			this.tbbPageCurrent.Text = "0";
			// 
			// chkCopyBarCode
			// 
			this.chkCopyBarCode.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.chkCopyBarCode.AutoSize = true;
			this.chkCopyBarCode.Location = new System.Drawing.Point(578, 755);
			this.chkCopyBarCode.Name = "chkCopyBarCode";
			this.chkCopyBarCode.Size = new System.Drawing.Size(112, 17);
			this.chkCopyBarCode.TabIndex = 42;
			this.chkCopyBarCode.Text = "BarCode is a copy";
			this.chkCopyBarCode.UseVisualStyleBackColor = true;
			// 
			// pmDate
			// 
			this.pmDate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.pmDate.Format = System.Windows.Forms.DateTimePickerFormat.Short;
			this.pmDate.Location = new System.Drawing.Point(684, 29);
			this.pmDate.Name = "pmDate";
			this.pmDate.Size = new System.Drawing.Size(98, 20);
			this.pmDate.TabIndex = 41;
			// 
			// lblBarCodes
			// 
			this.lblBarCodes.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
									| System.Windows.Forms.AnchorStyles.Right)));
			this.lblBarCodes.BackColor = System.Drawing.SystemColors.Menu;
			this.lblBarCodes.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
			this.lblBarCodes.Location = new System.Drawing.Point(580, 94);
			this.lblBarCodes.Multiline = true;
			this.lblBarCodes.Name = "lblBarCodes";
			this.lblBarCodes.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
			this.lblBarCodes.Size = new System.Drawing.Size(269, 655);
			this.lblBarCodes.TabIndex = 40;
			// 
			// txtBarCode
			// 
			this.txtBarCode.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.txtBarCode.Location = new System.Drawing.Point(580, 67);
			this.txtBarCode.Name = "txtBarCode";
			this.txtBarCode.Size = new System.Drawing.Size(270, 20);
			this.txtBarCode.TabIndex = 37;
			this.txtBarCode.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.txtBarCode_PreviewKeyDown);
			this.txtBarCode.Validated += new System.EventHandler(this.txtBarCode_Validated);
			// 
			// lblPMDate
			// 
			this.lblPMDate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.lblPMDate.AutoSize = true;
			this.lblPMDate.Location = new System.Drawing.Point(577, 33);
			this.lblPMDate.Name = "lblPMDate";
			this.lblPMDate.Size = new System.Drawing.Size(77, 13);
			this.lblPMDate.TabIndex = 39;
			this.lblPMDate.Text = "Postmark Date";
			// 
			// lblBarCodesHeader
			// 
			this.lblBarCodesHeader.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.lblBarCodesHeader.AutoSize = true;
			this.lblBarCodesHeader.Location = new System.Drawing.Point(578, 51);
			this.lblBarCodesHeader.Name = "lblBarCodesHeader";
			this.lblBarCodesHeader.Size = new System.Drawing.Size(56, 13);
			this.lblBarCodesHeader.TabIndex = 38;
			this.lblBarCodesHeader.Text = "BarCodes:";
			// 
			// timerAcquire
			// 
			this.timerAcquire.Tick += new System.EventHandler(this.timerAcquire_Tick);
			// 
			// MainForm
			// 
			this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
			this.ClientSize = new System.Drawing.Size(853, 784);
			this.Controls.Add(this.chkCopyBarCode);
			this.Controls.Add(this.pmDate);
			this.Controls.Add(this.lblBarCodes);
			this.Controls.Add(this.txtBarCode);
			this.Controls.Add(this.lblPMDate);
			this.Controls.Add(this.lblBarCodesHeader);
			this.Controls.Add(this.toolStrip1);
			this.Controls.Add(this.imGearPageView);
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Menu = this.mainMenu;
			this.Name = "MainForm";
			this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
			this.toolStrip1.ResumeLayout(false);
			this.toolStrip1.PerformLayout();
			this.ResumeLayout(false);
			this.PerformLayout();

		}
		#endregion

		[STAThread]
		static void Main() {
			try {
				//ImGearLicense.SetSolutionName("AccuSoft 3-40-2");
				ImGearLicense.SetSolutionName("Onrebate.com");
				ImGearLicense.SetSolutionKey(0x8150A590, 0x51AAF581, 0x6A5DB058, 0x59A10F61);
				ImGearLicense.SetOEMLicenseKey("1.0.Ea2oGrYZxHIedefjv0hrkOG9dafyW9WBfjhDbmIjWaPHkmPekeYoFmYmPyWZFmbmIoF5keGHYO49q9vyxDFyWC4DkmFe4yk5FOboIZ4rx9q9G0PHFCW5fa4ahBkyqZYr20GeIBf0Febmd5dCGCFadodDYaxO49I5Prf5doI52RhHYBxa2DWCPeIrFmvahaGHGjfOb5Wmd9YjPCbBdObBhZh9b0hB4mIHfBkmxmI529faPjGrYm2Cq0fmYZkehaFeGBPmfBI5xZWDk5fo2mYCP9b5WOWrd9YmY5YCdCk5YHx5G5IZk9keqrxCGrdehChahmqHGBYZxDxe25qmbOhyy");

				// Register warning handler
				ImGearWarning.AddWarning = new ImGearAddWarning(ImGearWinForms.AddWarning);

				// Registers exception handler for all threads.
				ImGearWinForms.RegisterExceptionHandler();
				Application.Run(new MainForm());
			} catch(Exception ex) {
				ImGearWinForms.ShowExceptionInfo(null,ex);
			}
			try {
				if(isSourceOpen && imGearTWAIN != null)
					imGearTWAIN.CloseSource();
			} catch {
			}
		}

		private void UpdatePageDisplay() {
			imGearPageView.Page = currImGearPage;
			imGearPageView.Update();

			menuSavePage.Enabled = (null != currImGearPage);
			menuSaveDocument.Enabled = (null != currImGearDoc);

			PageCount = currImGearDoc.Pages.Count;
			PageCurrent = currImGearDocPageNum;
		}

		private void Exit(object sender,System.EventArgs e) {
			this.Close();
		}

		private void SelectSource(object sender,System.EventArgs e) {
			if(isSourceOpen) {
				imGearTWAIN.CloseSource();
				isSourceOpen = false;
			}

			imGearTWAIN.OpenSource("");
			isSourceOpen = true;
		}

		Properties.Settings Settings = new Properties.Settings();
		private string SaveTo {
			get {
				if((Settings.SaveTo + "") == "") {
					FolderBrowserDialog fbd = new FolderBrowserDialog();
					fbd.Description = "Select directory to save image files";
					if(fbd.ShowDialog(this) != DialogResult.OK) return "";
					SaveTo = fbd.SelectedPath;
				}
				return Settings.SaveTo;
			}
			set {
				Settings.SaveTo = value;
				Settings.Save();
			}
		}
		private int BarCodeThreadsCount {
			get { return Convert.ToInt32(tbbBarCodeThreadsCount.Text); }
			set { tbbBarCodeThreadsCount.Text = value + ""; }
		}
		private int PageCount {
			get { return Convert.ToInt32(tbbPageCount.Text); }
			set { tbbPageCount.Text = value + ""; }
		}
		private int PageCurrent {
			get { return Convert.ToInt32(tbbPageCurrent.Text); }
			set { tbbPageCurrent.Text = value + ""; }
		}
		private Dimok.BarCodes dsBarCodes = new Dimok.BarCodes();
		private void ReadBarCodes() {
			SetEnabled(txtBarCode,false);
			try {
				BarCodeThreadsCount++;
				ImGearPage page = currImGearPage;
				Dimok.BarCodes.BarCodeDataTable dt = Dimok.BarCode.Read(page);
				dsBarCodes.Merge(dt);
				BarCodeThreadsCount--;
			} catch(Exception exc) { MessageBox.Show(this,exc.ToString()); }
			string barCodes = dsBarCodes.GetXml();
			SetText(lblBarCodes,barCodes);
			if( BarCodeThreadsCount == 0 )SetEnabled(txtBarCode,true);
			//AutoCropStarter();
		}

		private void mnuScanContinuous_Click(object sender,EventArgs e) {
			Acquire();
			//new Thread(new ThreadStart(Acquire)).Start();
		}
		private void Acquire(){
			enableScanEvents(false);
			imGearTWAIN.AfterPage += new ImGearTWAINAfterPageEventHandler(imGearTWAIN_After);
			imGearTWAIN.UseUI = menuItemUseUI.Checked;
			if(!isSourceOpen) SelectSource(null,null);
			try {
				imGearTWAIN.Acquire(-1);
			} catch(ImGearException exc) { MessageBox.Show(this,exc.Message); }
			this.Focus();
			this.Activate();
			imGearTWAIN.AfterPage -= new ImGearTWAINAfterPageEventHandler(imGearTWAIN_After);
		}

		private void AcquireSinglePage(object sender,System.EventArgs e) {
			currImGearPage = imGearTWAIN.AcquireToPage();
			currImGearDoc = null;
			GC.Collect();

			UpdatePageDisplay();
		}

		private void AcquireMultiPage(object sender,System.EventArgs e) {
			currImGearDoc = imGearTWAIN.AcquireToDoc(-1);
			currImGearDocPageNum = 0;
			currImGearPage = currImGearDoc.Pages[0];
			GC.Collect();

			UpdatePageDisplay();
		}

		#region Scanner Event Handlers ============================================================
		private void imGearTWAIN_After(object sender,ImGearTWAINAfterPageEventArgs e) {
			if(currImGearDoc == null) currImGearDoc = new ImGearDocument();
			currImGearPage = e.Page;
			currImGearDoc.Pages.Add(e.Page);
			ReadBarCodes();
			currImGearDocPageNum = currImGearDoc.Pages.Count;
			menuItemViewLastPage_Click(null,null);
			UpdatePageDisplay();
			System.Windows.Forms.Application.DoEvents();
		}
		private void imGearTWAIN_BeforePage(object sender,ImGearTWAINBeforePageEventArgs e) {
			string msgboxText = "You are about to scan page " + e.PageNumber + ".\n\nDo you want to continue?";
			if(MessageBox.Show(this,msgboxText,"BeforePage Event",MessageBoxButtons.YesNo) == DialogResult.No)
				e.CancelScanning = true;
		}

		private void imGearTWAIN_AfterPage(object sender,ImGearTWAINAfterPageEventArgs e) {
			currImGearPage = e.Page;
			UpdatePageDisplay();

			string msgboxText = "You just scanned page " + e.PageNumber + ".\n";
			if(e.PendCount == -1)
				msgboxText += "The number of remaining pages is unknown.\n\n";
			else
				msgboxText += "There are " + e.PendCount + " pages remaining.\n\n";
			msgboxText += "Do you want to continue?";

			if(MessageBox.Show(this,msgboxText,"AfterPage Event",MessageBoxButtons.YesNo) == DialogResult.No)
				e.CancelScanning = true;
		}
		#endregion =================================================================================

		private void AcquireMultiPageEvents(object sender,System.EventArgs e) {
			currImGearPage = null;
			currImGearDoc = null;
			UpdatePageDisplay();

			// Enable scan events if they're disabled
			bool originalEventsEnabled = bEventsEnabled;
			if(!bEventsEnabled)
				enableScanEvents(true);

			try {
				imGearTWAIN.Acquire(-1);
				GC.Collect();
			} finally {
				// Disable scan events if they were originally disabled
				if(!originalEventsEnabled)
					enableScanEvents(false);
			}
		}

		private void UseUI(object sender,System.EventArgs e) {
			menuItemUseUI.Checked = !menuItemUseUI.Checked;
			imGearTWAIN.UseUI = menuItemUseUI.Checked;
		}

		private void enableScanEvents(bool enable) {
			if(enable && !bEventsEnabled) {
				imGearTWAIN.BeforePage += new ImGearTWAINBeforePageEventHandler(imGearTWAIN_BeforePage);
				imGearTWAIN.AfterPage += new ImGearTWAINAfterPageEventHandler(imGearTWAIN_AfterPage);
				bEventsEnabled = true;
			} else if(!enable && bEventsEnabled) {
				imGearTWAIN.BeforePage -= new ImGearTWAINBeforePageEventHandler(imGearTWAIN_BeforePage);
				imGearTWAIN.AfterPage -= new ImGearTWAINAfterPageEventHandler(imGearTWAIN_AfterPage);
				bEventsEnabled = false;
			}
			menuItemUseEvents.Checked = bEventsEnabled;
		}

		private void menuItemUseEvents_Click(object sender,System.EventArgs e) {
			enableScanEvents(!menuItemUseEvents.Checked);
		}

		private void ShowWarnings(object sender,System.EventArgs e) {
			ImGearWinForms.ShowWarningInfo(this);
		}

		private void ShowAboutBox(object sender,System.EventArgs e) {
			ImGearWinForms.ShowAboutBox(this,applicationTitle);
		}

		private void menuItemScan_Popup(object sender,System.EventArgs e) {
			menuItemSinglePageAcquire.Enabled = isSourceOpen;
			menuItemMultiPageAcquire.Enabled = isSourceOpen;
			menuItemMultiPageAcquireEvents.Enabled = isSourceOpen;
		}

		private void menuSavePage_Click(object sender,System.EventArgs e) {
			ImGearWinForms.SavePage(this,currImGearPage);
		}

		private void menuSaveDocument_Click(object sender,System.EventArgs e) {
			ImGearSavingSelection selection = ImGearWinForms.SelectFileToSave(
				this,"Save Document",currImGearDoc);
			using(FileStream fileContent =
						 ((ImGearLocalFile)selection.File).OpenToWrite()) {
				ImGearFileFormats.SaveDocument(currImGearDoc,fileContent,0,
					ImGearSavingModes.OVERWRITE,selection.Format,null);
			}
		}

		private void menuItemView_Popup(object sender,System.EventArgs e) {
			if(currImGearDoc == null || currImGearDoc.Pages.Count == 0) {
				menuItemViewFirstPage.Enabled = false;
				menuItemViewPreviousPage.Enabled = false;
				menuItemViewNextPage.Enabled = false;
				menuItemViewLastPage.Enabled = false;
			} else {
				menuItemViewFirstPage.Enabled = (currImGearDocPageNum != 0);
				menuItemViewPreviousPage.Enabled = (currImGearDocPageNum > 0);
				menuItemViewNextPage.Enabled = (currImGearDocPageNum < (currImGearDoc.Pages.Count - 1));
				menuItemViewLastPage.Enabled = (currImGearDocPageNum < (currImGearDoc.Pages.Count - 1));
			}
		}

		private void setCurrentPage(int pageNum) {
			if(currImGearDoc == null)
				return;
			if(pageNum < 0)
				pageNum = 0;
			if(pageNum >= currImGearDoc.Pages.Count)
				pageNum = currImGearDoc.Pages.Count - 1;
			currImGearDocPageNum = pageNum;
			currImGearPage = currImGearDoc.Pages[currImGearDocPageNum];
			UpdatePageDisplay();
		}

		private void menuItemViewFirstPage_Click(object sender,System.EventArgs e) {
			setCurrentPage(0);
		}

		private void menuItemViewPreviousPage_Click(object sender,System.EventArgs e) {
			setCurrentPage(currImGearDocPageNum - 1);
		}

		private void menuItemViewNextPage_Click(object sender,System.EventArgs e) {
			setCurrentPage(currImGearDocPageNum + 1);
		}

		private void menuItemViewLastPage_Click(object sender,System.EventArgs e) {
			setCurrentPage(currImGearDoc.Pages.Count - 1);
		}

		private void mnuScanParams_Click(object sender,System.EventArgs e) {
			frmScanParams sParams = new frmScanParams(this);
			sParams.ShowDialog();
			sParams.Dispose();
		}

		private void menuItemSettings_Popup(object sender,System.EventArgs e) {
			mnuScanParams.Enabled = isSourceOpen;
		}

		public ImGearTWAIN IMGearTWAIN {
			get {
				return imGearTWAIN;
			}
		}

		private void tbbPrev_Click(object sender,EventArgs e) {
			menuItemViewPreviousPage_Click(null,null);
		}

		private void tbbNext_Click(object sender,EventArgs e) {
			menuItemViewNextPage_Click(null,null);
		}

		void SendTab(object sender,EventArgs e) {
			txtBarCode.Focus();
			SendKeys.SendWait("{TAB}");
		}
		private void txtBarCode_PreviewKeyDown(object sender,PreviewKeyDownEventArgs e) {
			if(e.KeyCode == Keys.Enter && txtBarCode.Text == "") {
				Acquire();
				return;
			}
			if(e.KeyCode == Keys.Enter) txtBarCode.Invoke(new EventHandler(SendTab));
			if(e.KeyCode == Keys.S && e.Control)SaveDocument();
			if(e.KeyCode == Keys.Down) pmDate.Value = pmDate.Value.AddDays(1);
			if(e.KeyCode == Keys.Up) pmDate.Value = pmDate.Value.AddDays(-1);
		}
		private void txtBarCode_Validated(object sender,EventArgs e) {
			if(((TextBox)sender).Text == "") return;
			dsBarCodes.BarCode.AddBarCodeRow(((TextBox)sender).Text,0,"");
			lblBarCodes.Text = dsBarCodes.GetXml();
			((TextBox)sender).Text = "";
		}

		void SetFocus(object sender,EventArgs e) {
			((TextBox)sender).Focus();
		}
		private void timerBarCodeBox_Tick(object sender,EventArgs e) {
			try {
				txtBarCode.Invoke(new EventHandler(SetFocus));
			} catch { }
		}

		private void tbbClearAll_Click(object sender,EventArgs e) { ClearImages(); }

		private void ClearImages(){
			currImGearDoc.Pages.Clear();
			currImGearPage = null;
			dsBarCodes.Clear();
			txtBarCode.Text = "";
			lblBarCodes.Text = "";
			chkCopyBarCode.Checked = false;
			UpdatePageDisplay();
		}

		private void toolStrip1_Paint(object sender,PaintEventArgs e) {
			bool showNav = currImGearDoc != null && currImGearDoc.Pages.Count > 0;
			tbbClearAll.Enabled = showNav;
			tbbNext.Enabled = showNav;
			tbbPrev.Enabled = showNav;
		}

		private void tbbSave_Click(object sender,EventArgs e) { SaveDocument(); }
		private void SaveDocument(){
			if(currImGearDoc == null || currImGearDoc.Pages.Count == 0) { MessageBox.Show(this,"There is no images to save."); return; }
			string fileBase = SaveTo + "\\" + DateTime.Now.ToString("yyMMdd_HHmmss");
			using(FileStream fs = File.Create(fileBase)) {
				ImageGear.Formats.ImGearFileFormats.SaveDocument(currImGearDoc,fs,0,ImGearSavingModes.OVERWRITE,ImGearSavingFormats.TIF_UNCOMP,new ImGearSaveOptions());
			}
			File.Move(fileBase,fileBase + ".tif");
			dsBarCodes.BarCode.AddBarCodeRow(pmDate.Text,(int)BarCodeTypes.PostmarkDate,"PostmarkDate");
			dsBarCodes.BarCode.AddBarCodeRow(Environment.UserDomainName + "\\" + Environment.UserName, (int)BarCodeTypes.UserName, "UserName");
			dsBarCodes.BarCode.AddBarCodeRow(DateTime.Now.ToShortDateString(), (int)BarCodeTypes.ScanDate, BarCodeTypes.ScanDate + "");
			dsBarCodes.BarCode.AddBarCodeRow(currImGearDoc.Pages.Count+"", (int)BarCodeTypes.PageCount, BarCodeTypes.PageCount + "");
			dsBarCodes.BarCode.AddBarCodeRow(chkCopyBarCode.Checked + "",(int)BarCodeTypes.BarCodeCopy,"BarCodeCopy");
			dsBarCodes.BarCode.AddBarCodeRow(DateTime.Now.ToShortDateString(), (int)BarCodeTypes.ScanDate, BarCodeTypes.ScanDate + "");
			File.WriteAllText(fileBase + ".bc",dsBarCodes.GetXml());
			ClearImages();
			timerAcquire.Start();
		}
		#region UI
		delegate void SetTextCallback(Control c,string text);
		void SetText(Control c,string text) {
			if(c.InvokeRequired) {
				SetTextCallback d = new SetTextCallback(SetText);
				c.Invoke(d,c,text);
			} else c.Text = text;
		}
		delegate void SetEnableCallback(Control c,bool enabled);
		void SetEnabled(Control c,bool enabled) {
			if(c.InvokeRequired) {
				SetEnableCallback d = new SetEnableCallback(SetEnabled);
				c.Invoke(d,c,enabled);
			} else c.Enabled = enabled;
		}
		#endregion

		private void tbbScan_Click(object sender,EventArgs e) {
			Acquire();
		}

		private void timerAcquire_Tick(object sender,EventArgs e) {
			timerAcquire.Stop();
			Acquire();
		}

		private void mnuOutputFolder_Click(object sender, EventArgs e) {
			FolderBrowserDialog fbd = new FolderBrowserDialog();
			fbd.Description = "Select directory to save image files";
			if (fbd.ShowDialog(this) == DialogResult.OK) SaveTo = fbd.SelectedPath;
		}
	}
}
